var util = require('../../utils/util.js');
var utilMd5 = require('../../utils/md5.js');
var base64 = require('../../utils/Base64.js');
var WxParse = require('../../wxParse/wxParse.js');
var app = getApp();
var wxFailAuth = true;
Page({

  /**
     * 页面的初始数据
     */
  data: {
    uid: 0,
    token: 0,
    openid: 0,
    userinfo: {},
    article: '',
    peopleAvatar:[],

    hongbaoData: {}, //红包数据
    hongbaoId: '',//红包id
    shareuid: '', //分享者id
    huaCount: 0, //花的数量
    getHongBaoCount: 0,//当前这个分享者领取红包个数
    getTotalMoney: 0, //当前这个分享者领取的红包总额
    hongbaoJin_e: 0, //当次开红包所得金额

    hasMingPian: false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    this.setData({
      //红包id
      hongbaoId: options.hongbaoid,
      //分享者id
      shareuid: options.shareuid
    });

    app.LoginUserInfo(function (res) {
      wxFailAuth = res == -1;
      if(!wxFailAuth){
        var cata = (parseInt(res.usercata) > 0) ? true : false;
        that.setData({
          userinfo: res,
          uid: res.uid,
          token: res.token,
          openid: res.wxsmall_openid,
          hasMingPian: cata
        });

        that.getHongbaoInfo(that.data.uid, that.data.token);  
      } else {
        that.getHongbaoInfo("", that.data.token);  
      }
    });
  },

  goTixianPage: function(e) {
    // {{uid }}
    if (wxFailAuth) {
      app.reAuthorize(this.reGetUserInfo);
    } else {
      wx.navigateTo({ url: "/pages/tixian/tixian?uid=" + this.data.uid });
      app.saveFormId(e.detail.formId);
    }
  },

  goAtherPage: function (e) {
    var url = e.currentTarget.dataset.link;
    if (url) {
      wx.navigateTo({ url: url })
    }
  },
  goAtherPageRedirect: function (e) {
    var url = e.currentTarget.dataset.link;
    wx.redirectTo({ url: url })
  },

  //获取红包信息
  getHongbaoInfo: function (uid, token) {
    var that = this;
    var privatekey = utilMd5.hexMD5(uid + 'hongbaocontent' + token);
    util.api({
      method: "POST",
      data: {
        ac: "hongbaocontent",
        shareuid: that.data.shareuid,
        hongbaoid: that.data.hongbaoId,
        uid: uid,
        privatekey: privatekey
      },
      success: function (responseData) {
        if (responseData && responseData.statusCode == 200) {
          if (responseData.data.msg) {
            app.dialog(responseData.data.msg, "loading");
          }
          //更新数据
          console.log('hongbao: ', responseData);
          var getOver = "";
          var allCount = parseInt(responseData.data.all_count);
          var allGetCount = parseInt(responseData.data.all_getcount);
          var myGetCoin = parseInt(responseData.data.myget_coin);
          if (allGetCount >= allCount) {
            if (myGetCoin > 0) {
              getOver = (myGetCoin / 100.0).toFixed(2);
            } else { 
              getOver = "领完了";
            }
          } else {
            if (myGetCoin > 0) {
              getOver = (myGetCoin / 100.0).toFixed(2);
            }
          }
          // 转换金额单位
          var shareInfo = responseData.data.shareinfo;
          if(shareInfo) {
            for (var i = 0; i < shareInfo.length; i++) {
              var formatShareNum = (parseInt(shareInfo[i].sharenum) / 100.0).toFixed(2);
              shareInfo[i].sharenum_yuan = formatShareNum;
            }
          }

          var totalMoney = (responseData.data.this_allget_coin / 100.0).toFixed(2);
          that.setData({
            hongbaoData: responseData.data,
            article: responseData.data.html_data,
            huaCount: responseData.data.flower_num,
            getHongBaoCount: responseData.data.this_allget_count,
            getTotalMoney: totalMoney,
            hongbaoJin_e: getOver
          });
          /**
              * WxParse.wxParse(bindName , type, data, target,imagePadding)
              * 1.bindName绑定的数据名(必填)
              * 2.type可以为html或者md(必填)
              * 3.data为传入的具体数据(必填)
              * 4.target为Page对象,一般为this(必填)
              * 5.imagePadding为当图片自适应是左右的单一padding(默认为0,可选)
              */
          WxParse.wxParse('article', 'html', that.data.article, that, 0);

          //设置导航标题
          var userName = responseData.data.senduser.username;
          var navtitle = userName + '发福利';
          wx.setNavigationBarTitle({
            title: navtitle
          });
        }
        console.log(responseData)
      }
    });
  },

  reGetUserInfo: function (e) {
    var that = this;
    console.log("reGetUserInfo: ", e);
    if (e == 1) {
      // wx.reLaunch({ //用这个会报错fail can not invoke relaunch in background
      wx.redirectTo({
        url: '/pages/hongbao/hongbao?hongbaoid=' + that.data.hongbaoId + '&shareuid=' + that.data.shareuid
      })
    }
  },

  //开红包
  kaihongbaoAction: function (e) {
    if(wxFailAuth){
      app.reAuthorize(this.reGetUserInfo);
      return;
    }
    wx.showLoading({
      title: '开。。。',
    })
    console.log("formId ", e.detail.formId);
    app.saveFormId(e.detail.formId);//保存fromId

    var that = this;
    var privatekey = utilMd5.hexMD5(that.data.uid + 'gethongbao' + that.data.token);
    util.api({
      method: "POST",
      data: {
        ac: "gethongbao",
        uid: that.data.uid,
        hongbaoid: that.data.hongbaoId,
        shareuid: that.data.shareuid,
        openid: that.data.openid,
        privatekey: privatekey
      },
      success: function (responseData) {
        console.log("gethongbao ", responseData);
        if (responseData && responseData.statusCode == 200) {
          if (responseData.data.res) {
            var totalMoney = (responseData.data.coin_num / 100.0).toFixed(2);
            app.dialog("你帮" + that.data.hongbaoData.shareuser.username + "拆了" + totalMoney + "元", " ");
            
            //刷新数据
            that.getHongbaoInfo(that.data.uid, that.data.token);
          } else {
            if (responseData.data.msg.indexOf("empty") >= 0) {
              var showStr = "领完了";
              that.setData({
                hongbaoJin_e: showStr
              });
            }
            app.dialog(responseData.data.msg, " ");
            
          }
        }
        wx.hideLoading();
      }
    });
  },

  //送花
  songhuaAction: function () {
    if (wxFailAuth) {
      app.reAuthorize(this.reGetUserInfo);
      return;
    }

    var that = this;
    var privatekey = utilMd5.hexMD5(that.data.uid + 'hongbaozan' + that.data.token);
    util.api({
      method: "POST",
      data: {
        ac: "hongbaozan",
        uid: that.data.uid,
        hongbaoid: that.data.hongbaoId,
        privatekey: privatekey
      },
      success: function (responseData) {
        console.log("songhua ", responseData);
        if (responseData && responseData.statusCode == 200) {
          if (responseData.data.res) {
            that.setData({
              huaCount: (parseInt(that.data.huaCount) + 1)
            });
          } else {
            app.dialog(responseData.data.msg, " ");
          }
        }
        
      }
    });
  },

  shareToPengyouquan: function (e) {
    console.log("formId ", e.detail.formId);
    app.saveFormId(e.detail.formId);//保存fromId
    var that = this;
    
    // var shareImgUrl = "http://api.artart.cn/wxxcxcode.php?pyq=1&uid=" + that.data.uid;
    var shareImgUrl = "http://api.artart.cn/wxxcxcode.php?haibao=1&uid=" + that.data.uid +
      "&shareuid=" + that.data.uid + "&hongbaoid=" + that.data.hongbaoId;
    this.showEWM(shareImgUrl);
    // shareImgUrl = base64.encode(shareImgUrl);
    // var url = "/pages/share-pengyouquan/share-pengyouquan?imgUrl=" + shareImgUrl;
    // wx.navigateTo({ url: url })
  },

  //页面分享
  onShareAppMessage: function () {
    console.log("onShareAppMessage");
    var that = this;
    return app.sharePage({
      title: "你若颜值高，众人帮拆包。速来比拼？",
      path: '/pages/hongbao/hongbao?hongbaoid=' + that.data.hongbaoId + '&shareuid=' + that.data.uid + '&inviteuid=' + that.data.uid
    });
  },

  //保存formId
  submitFormId: function (e) {
    console.log("formId: ", e.detail.formId);
    app.saveFormId(e.detail.formId);
  },

  showEWM: function (url) {
    wx.previewImage({
      current: url,
      urls: [url]
    })
  },
})